// lib/ui/order/order_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/order/order_list_bean_entity.dart';
import 'package:flutter_deer/database/order_status.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/ui/cashier/provider/common_http_provider.dart';
import 'package:flutter_deer/util/print/data/order_type_option.dart';
import 'package:get/get.dart';

class OrderListPage extends StatefulWidget {
  final Function(OrderListBeanList)? onOrderSelected;

  const OrderListPage({super.key, this.onOrderSelected});

  @override
  _OrderListPageState createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage>
    with AutomaticKeepAliveClientMixin<OrderListPage> {
  List<OrderListBeanList> _orders = [];
  bool _isLoading = false;
  int _currentPage = 1;
  bool _hasMore = true;
  int? _selectedType;
  int? _selectedStatus;
  final ScrollController _scrollController = ScrollController();

  // 添加选中的订单ID集合
  String _selectedOrderIds = '';

  final commonHttpProvider = Get.find<CommonHttpProvider>();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadOrders(); //加载数据
    });
    _scrollController.addListener(_scrollListener);
  }

  @override
  void dispose() {
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      _loadMoreOrders();
    }
  }

  Future<void> _loadOrders() async {
    setState(() {
      _isLoading = true;
    });

    commonHttpProvider.getOrderList(
      pageNo: _currentPage,
      orderType: _selectedType,
      orderStatus: _selectedStatus,
      success: (data) {
        print('获取订单列表成功 data: ${data.list?.length} / ${data.total}');

        final List<OrderListBeanList> newOrders = data.list ?? [];

        setState(() {
          if (_currentPage == 1) {
            _orders = newOrders;
          } else {
            _orders.addAll(newOrders);
          }
          _isLoading = false;
          _hasMore = newOrders.length == 10; // 假设每页10条数据
        });
      },
    );
  }

  Future<void> _loadMoreOrders() async {
    if (!_isLoading && _hasMore) {
      setState(() {
        _currentPage++;
      });
      await _loadOrders(); //加载更多数据
    }
  }

  void _onTypeSelected(int? type) {
    setState(() {
      _selectedType = type;
      _currentPage = 1;
    });
    _loadOrders(); //筛选数据
  }

  void _onStatusSelected(int? status) {
    setState(() {
      _selectedStatus = status;
      _currentPage = 1;
    });
    _loadOrders(); //筛选数据
  }

  void _resetFilters() {
    setState(() {
      _selectedType = null;
      _selectedStatus = null;
      _currentPage = 1;
    });
    _loadOrders(); //筛选数据
  }

  // 添加切换订单选中状态的方法
  void _toggleOrderSelection(String orderId) {
    setState(() {
      _selectedOrderIds = orderId;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SizedBox(
      width: 500,
      child: Column(
        children: [
          // 筛选条件
          _buildFilterSection(),
          // 订单列表
          Expanded(
            child: _buildOrderList(),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterSection() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text('筛选条件',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              TextButton(onPressed: _resetFilters, child: const Text('重置')),
            ],
          ),
          const SizedBox(height: 8),
          // 类型筛选
          _buildFilterRow('类型', OrderTypeOption.getValues(), _selectedType,
              (value) {
            _onTypeSelected(value);
          }),
          const SizedBox(height: 8),
          // 状态筛选
          _buildFilterRow('状态', OrderPayStatus.getValues(), _selectedStatus,
              (value) {
            _onStatusSelected(value);
          }),
        ],
      ),
    );
  }

  Widget _buildFilterRow(String label, List<int> options, int? selectedValue,
      Function(int?) onChanged) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(top: 6),
          child: Text('$label:'),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Wrap(
            spacing: 8,
            runSpacing: 4,
            children: [
              FilterChip(
                label: const Text('全部'),
                selected: selectedValue == null,
                onSelected: (selected) => onChanged(null),
              ),
              ...options.map((option) {
                final String label = _getOptionLabel(option);
                return FilterChip(
                  label: Text(label),
                  selected: selectedValue == option,
                  onSelected: (selected) => onChanged(option),
                );
              }).toList(),
            ],
          ),
        ),
      ],
    );
  }

  String _getOptionLabel(int option) {
    // OrderTypeOption
    if (option < 1000) {
      switch (option) {
        case 10:
          return '油品';
        case 20:
          return '充值';
        case 30:
          return '便利店';
        case 92:
          return '通付';
      }
    } else if (option > 1000) {
      switch (option) {
        case 1010:
          return '待支付';
        case 1020:
          return '支付中';
        case 1030:
          return '已完成';
        case 1040:
          return '已取消';
        case 3080:
          return '已退款';
      }
    }
    return '$option';
  }

  Widget _buildOrderList() {
    if (_isLoading && _currentPage == 1) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_orders.isEmpty) {
      return _buildEmptyView();
    }

    return RefreshIndicator(
      onRefresh: () async {
        _currentPage = 1;
        await _loadOrders(); //刷新数据
      },
      child: ListView.builder(
        controller: _scrollController,
        itemCount: _orders.length + (_hasMore ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _orders.length) {
            // 加载更多指示器
            return _buildLoadMoreIndicator();
          }
          return _buildOrderItem(_orders[index]);
        },
      ),
    );
  }

  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.receipt_long,
            size: 80,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无订单数据',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '您可以尝试调整筛选条件',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLoadMoreIndicator() {
    return const Padding(
      padding: EdgeInsets.all(16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(strokeWidth: 2),
          ),
          SizedBox(width: 12),
          Text('加载中...'),
        ],
      ),
    );
  }

  Widget _buildOrderItem(OrderListBeanList order) {
    final OrderTypeColors colors =
        _getOrderTypeColors(order.orderType ?? 0);
    // 检查订单是否被选中
    final bool isSelected = _selectedOrderIds == order.orderId;

    return Container(
      height: 142.0,
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: isSelected ? Colors.blue.withOpacity(0.1) : colors.backgroundColor,
        border: Border.all(
          color: isSelected ? Colors.blue : colors.borderColor,
          width: isSelected ? 1 : 1,
        ),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: colors.shadowColor.withOpacity(0.2),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        onTap: () {
          // 切换选中状态
          _toggleOrderSelection(order.orderId);
          widget.onOrderSelected?.call(order);
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Stack(
            children: [
              Positioned(
                top: 0.0,
                left: 0.0,
                child: Row(
                  children: [
                    // 订单类型
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: colors.badgeColor,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(OrderTypeOption.getDesc(order.orderType),
                          style: const TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                              fontWeight: FontWeight.bold)),
                    ),
                    const SizedBox(width: 8),
                    // 客户类型
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text('${order.clientTypeName}',
                          style: const TextStyle(
                              color: Colours.text,
                              fontSize: 12,
                              fontWeight: FontWeight.bold)),
                    ),
                    const SizedBox(width: 8),
                    // 手机号
                    Text('${order.phone}',
                        style: const TextStyle(
                            color: Colours.text,
                            fontSize: 12,
                            fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
              Positioned(
                top: 0.0,
                right: 0.0,
                child: Text(OrderPayStatus.getDesc(order.orderStatus),
                    style: TextStyle(
                        color: _getStatusColor(order.orderStatus),
                        fontSize: 15,
                        fontWeight: FontWeight.bold)),
              ),
              Positioned(
                bottom: 0.0,
                left: 0.0,
                child: Text('订单号: ${order.orderId}',
                    style:
                        TextStyle(color: Colors.grey[600], fontSize: 14)),
              ),
              Positioned(
                bottom: 0.0,
                right: 0.0,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text('¥${order.orderAmount}',
                        style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: colors.amountColor)),
                    const SizedBox(height: 4),
                    Text('${order.orderTime}',
                        style:
                            TextStyle(color: Colors.grey[500], fontSize: 12)),
                  ],
                ),
              ),
              Positioned(
                top: 30,
                left: 0,
                bottom: 22,
                right: 110,
                child: Align(
                    alignment: Alignment.centerLeft,
                    child: _buildOilOrderItem(order)),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构造油品订单布局
  Widget _buildOilOrderItem(OrderListBeanList order) {
    if (order.orderType == 10 || order.orderType == 11) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('${order.mchGoodsName}',
              style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colours.text)),
          const SizedBox(height: 6),
          Text('${order.mchGoodsNum}',
              style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.normal,
                  color: Colours.text)),
        ],
      );
    }
    if (order.orderType == 20) {
      final String title = order.cashBackAmount?.isNotEmpty == true
          ? '充值金额：￥${order.orderAmount} (赠${order.cashBackAmount}元)'
          : '充值金额：￥${order.orderAmount}';
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('${order.mchGoodsName}',
              style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colours.text)),
          const SizedBox(height: 6),
          Text(title,
              style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.normal,
                  color: Colours.text)),
        ],
      );
    }
    if (order.orderType == 30) {
      if (order.orderGoodsDetailResponse != null &&
          order.orderGoodsDetailResponse!.isNotEmpty) {
        return LayoutBuilder(
          builder: (context, constraints) {
            final maxInt = 5;
            // 限制最多显示4个项目
            final itemsToShow = order.orderGoodsDetailResponse!.length > maxInt
                ? order.orderGoodsDetailResponse!.sublist(0, maxInt)
                : order.orderGoodsDetailResponse!;

            return SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ...itemsToShow.asMap().entries.map((entry) {
                    final index = entry.key;
                    final item = entry.value;
                    return Padding(
                      padding: EdgeInsets.only(
                        right: index < itemsToShow.length - 1 ? 12 : 0,
                      ),
                      child: _buildSimpleImageTextLayout(
                          imageUrl: item.coverImageUrl ?? '',
                          text: item.mchGoodsName ?? ''),
                    );
                  }).toList(),
                  // 如果原始列表数量超过4个，添加省略号
                  if (order.orderGoodsDetailResponse!.length > maxInt)
                    const Text(
                      '\t\t\t\t\t...',
                      style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.normal,
                          color: Colours.text),
                    ),
                ],
              ),
            );
          },
        );
      } else {
        return Text('${order.mchGoodsName}',
            style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colours.text));
      }
    }

    return Container();
  }

  // 添加一个简单的布局组件：40x40圆角灰色背景图片 + 最多80宽度的文本
  Widget _buildSimpleImageTextLayout(
      {required String imageUrl, required String text}) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        // 40x40圆角灰色背景图片
        Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: Colors.grey[300],
            borderRadius: BorderRadius.circular(8),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Image.network(
              imageUrl,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                // 图片加载失败时显示占位符
                return Icon(
                  Icons.image,
                  color: Colors.grey[600],
                  size: 20,
                );
              },
            ),
          ),
        ),
        // 最多80宽度的文本，尾部超出省略
        SizedBox(
          width: 60,
          child: Center(
              child: Text(text,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(fontSize: 14, color: Colours.text))),
        ),
      ],
    );
  }

  Color _getStatusColor(int? status) {
    switch (status) {
      case 1010:
        return Colors.orange;
      case 1020:
        return Colors.blue;
      case 1030:
        return Colors.green;
      case 1040:
      case 3080:
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  OrderTypeColors _getOrderTypeColors(int type) {
    switch (type) {
      // OrderTypeOption.oil
      case 10:
        return OrderTypeColors(
          backgroundColor: Colors.orange.withOpacity(0.1),
          borderColor: Colors.orange.withOpacity(0.3),
          badgeColor: Colors.orange,
          amountColor: Colors.orange,
          shadowColor: Colors.orange,
        );
      case 20:
        return OrderTypeColors(
          backgroundColor: Colors.purple.withOpacity(0.1),
          borderColor: Colors.purple.withOpacity(0.3),
          badgeColor: Colors.purple,
          amountColor: Colors.purple,
          shadowColor: Colors.purple,
        );
      case 30:
        return OrderTypeColors(
          backgroundColor: Colors.blue.withOpacity(0.1),
          borderColor: Colors.blue.withOpacity(0.3),
          badgeColor: Colors.blue,
          amountColor: Colors.blue,
          shadowColor: Colors.blue,
        );
      case 92:
        return OrderTypeColors(
          backgroundColor: Colors.pink.withOpacity(0.1),
          borderColor: Colors.pink.withOpacity(0.3),
          badgeColor: Colors.pink,
          amountColor: Colors.pink,
          shadowColor: Colors.pink,
        );
      default:
        return OrderTypeColors(
          backgroundColor: Colors.grey.withOpacity(0.1),
          borderColor: Colors.grey.withOpacity(0.3),
          badgeColor: Colors.grey,
          amountColor: Colors.grey,
          shadowColor: Colors.grey,
        );
    }
  }

  @override
  bool get wantKeepAlive => true;
}

// 订单类型颜色配置类
class OrderTypeColors {
  final Color backgroundColor;
  final Color borderColor;
  final Color badgeColor;
  final Color amountColor;
  final Color shadowColor;

  OrderTypeColors({
    required this.backgroundColor,
    required this.borderColor,
    required this.badgeColor,
    required this.amountColor,
    required this.shadowColor,
  });
}
